package net.chensee.avastxa.common.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import net.chensee.avastxa.common.exception.ClientCloseException;
import net.chensee.avastxa.common.exception.ServerStopException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

public class SocketClientStarter {
    private static final Logger logger = LoggerFactory.getLogger(SocketClientStarter.class);

    private EventLoopGroup workerGroup;
    private Channel channel;

    private int workerGroupThreads;
    private String host;
    private int port;

    private ChannelHandler channelHandler;

    public static SocketClientStarter newInstance(int workerGroupThreads, String host, int port) {
        return new SocketClientStarter(workerGroupThreads, host, port);
    }

    public SocketClientStarter(int workerGroupThreads, String host, int port) {
        this.workerGroupThreads = workerGroupThreads;
        this.host = host;
        this.port = port;
    }

    public SocketClientStarter setInitialzer(ChannelHandler channelHandler) {
        this.channelHandler = channelHandler;
        return this;
    }

    public void start() {
        workerGroup = new NioEventLoopGroup(workerGroupThreads);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(this.channelHandler);
        channel = bootstrap.connect(host, port)
                .syncUninterruptibly()
                .channel();

        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                SocketClientStarter.this.close();
            }
        });
    }

    public InetSocketAddress getRemoteAddress() {
        SocketAddress remoteAddress = channel.remoteAddress();
        if (!(remoteAddress instanceof InetSocketAddress)) {
            throw new RuntimeException("Get remote address error, should be InetSocketAddress");
        }
        return (InetSocketAddress) remoteAddress;
    }

    public void close() {
        if (null == channel) {
            throw new ClientCloseException();
        }
        workerGroup.shutdownGracefully();
        channel.closeFuture().syncUninterruptibly();
        workerGroup = null;
        channel = null;
    }
}
